package edu.umassd.raddacl.util;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.Collection;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import edu.umassd.raddacl.Cluster;

@Component
public class Output
{
	@Autowired
	private Locations locations;

	@PostConstruct
	protected void createDefaultDirs() throws IOException
	{
		Files.createDirectories(locations.getOutputFile().getParent());
	}

	public void save(Collection<Cluster> clusters)
	{
		Path saveFile = locations.getOutputFile();

		StandardOpenOption[] ops =
		{ StandardOpenOption.CREATE, StandardOpenOption.WRITE,
				StandardOpenOption.TRUNCATE_EXISTING };

		try
		{
			if (Files.exists(saveFile))
			{
				moveFile(saveFile);
			}

			BufferedWriter writer = Files.newBufferedWriter(saveFile,
					Charset.defaultCharset(), ops);

			for (Cluster c : clusters)
			{
				writer.write(c.toString());
				writer.newLine();
			}

			writer.flush();
			writer.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	private void moveFile(Path saveFile) throws IOException
	{
		int value = 1;

		Path p = Paths.get(saveFile.toString() + "." + value);

		while (Files.exists(p))
		{
			value++;
			p = Paths.get(saveFile.toString() + "." + value);
		}

		Files.move(saveFile, p, StandardCopyOption.REPLACE_EXISTING);
	}
}
